import Vue from 'vue'
import _ from 'lodash'
Vue.prototype._ = _

// 组装树结构
export function getTree({ headerData, includeDw }) {
  headerData = JSON.parse(JSON.stringify(headerData));
  const header = [];
  for (let i = 0, len = headerData.length; i < len; i++) {
    for (let j = 0, jlen = headerData[i].length; j < jlen; j++) {
      let item = headerData[i][j];
      if (!item.bdsdy) {
        item.bdsdy = UUID();
      }
      const flag = !includeDw
        ? !item.isMerge && item.prop !== "DWMC"
        : !item.isMerge;
      if (flag) {
        // 未合并且不是单位/地区列
        header.push(item);
      }
    }
  }
  for (let i = 0; i < header.length; i++) {
    let item = header[i];
    getParent(header, item);
  }
  return getTreeData(header, "id", "fid", undefined);
}
// 获取父元素
function getParent(header, item) {
  for (let curItem of header) {
    if (
      item.x === curItem.x + curItem.rowspan &&
      (item.y === curItem.y ||
        item.y + item.colspan <= curItem.y + curItem.colspan)
    ) {
      item.fid = curItem.id;
      item.fbdsdy = curItem.bdsdy;
      break;
    }
  }
}
// 获取叶子节点
export function getLeafNodes(treeData, leafNodes) {
  if (treeData?.length > 0) {
    treeData.forEach(item => {
      if (!item.children || item.children.length == 0) {
        leafNodes.push(item);
      } else {
        getLeafNodes(item.children, leafNodes);
      }
    });
  }
}
// 获取树节点数据字典
export function getTreeDataMap(treeData, dataMap) {
  treeData.forEach(el => {
    dataMap[el.bdsdy] = el;
    if (el.children?.length > 0) {
      getTreeDataMap(el.children, dataMap);
    }
  });
}

// 获取表格数据
export function getHeaderList(headerData) {
  const treeData = getTree({
    headerData,
    includeDw: true
  });
  let leafNodes = [];
  getLeafNodes(treeData, leafNodes);
  return leafNodes.map(el => {
    let prop = el.prop;
    if (el.hsgs) {
      prop = el.hsgs.replace("$1", twoEl.prop);
    }
    return prop;
  });
}
const UUID = function() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
    const r = (Math.random() * 16) | 0;
    const v = c == "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};
// 递归树形数据（data: 数据源，id：键值，pid：父键值，pvalue：一级节点pid的值）
const getTreeData = function(data, id, pid, pvalue) {
  const _data = {};
  data.map(item => {
    if (!_data[item[pid]]) _data[item[pid]] = [];
    _data[item[pid]].push(item);
  });
  const root = _data[pvalue];

  function inner(temp = []) {
    return temp.map(item => {
      item.children = _data[item[id]] || [];
      if (_data[item[id]]) inner(_data[item[id]]);
      return item;
    });
  }
  return inner(root);
};